import argparse
import torch
import os
import json
from tqdm import tqdm
from datasets import load_dataset

from dattn.constants import IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN
from dattn.model.builder import load_pretrained_model
from dattn.utils import disable_torch_init
from dattn.dataset.vis_utils import process_images, get_model_name_from_path
from dattn.dataset.txt_utils import tokenizer_image_token, preprocess_chat

import math


def split_list(lst, n):
    """Split a list into n (roughly) equal-sized chunks"""
    chunk_size = math.ceil(len(lst) / n)  # integer division
    return [lst[i:i+chunk_size] for i in range(0, len(lst), chunk_size)]


def get_chunk(lst, n, k):
    chunks = split_list(lst, n)
    return chunks[k]


def eval_model(args):
    # Model
    disable_torch_init()
    model_path = os.path.expanduser(args.model_path)
    model_name = get_model_name_from_path(model_path)
    model, tokenizer, image_processor = load_pretrained_model(model_path)
    
    data = load_dataset("Lin-Chen/MMStar", "val")["val"]
    data_idx = list(range(len(data)))
    data_idx = get_chunk(data_idx, args.num_chunks, args.chunk_idx)
    answers_file = os.path.expanduser(args.answers_file)
    os.makedirs(os.path.dirname(answers_file), exist_ok=True)
    ans_file = open(answers_file, "w")
    for idx in tqdm(data_idx, dynamic_ncols=True):
        line = data[idx]
        
        qs = line['question']
        cur_prompt = qs

        image = line["image"].convert('RGB')
        image_tensor = process_images([image], image_processor, model.config)[0]
        images = image_tensor.unsqueeze(0).half().cuda()
        image_sizes = [image.size]
        cur_prompt = '<image>' + '\n' + cur_prompt
        qs = DEFAULT_IMAGE_TOKEN + '\n' + qs

        if args.single_pred_prompt:
            qs = qs + '\n' + "Answer with the option's letter from the given choices directly."
            cur_prompt = cur_prompt + '\n' + "Answer with the option's letter from the given choices directly."

        prompt = preprocess_chat([{"from": "human", "value": qs}], tokenizer)

        input_ids = tokenizer_image_token(prompt, tokenizer, IMAGE_TOKEN_INDEX, return_tensors='pt').unsqueeze(0).cuda()

        with torch.inference_mode():
            output_ids = model.generate(
                input_ids,
                images=images,
                image_sizes=image_sizes,
                do_sample=True if args.temperature > 0 else False,
                temperature=args.temperature,
                max_new_tokens=4096,
                pad_token_id=tokenizer.pad_token_id,
                use_cache=True,
            )
        outputs = tokenizer.batch_decode(output_ids, skip_special_tokens=True)[0].strip()

        ans_file.write(json.dumps({"question_id": line["index"],
                                   "prompt": cur_prompt,
                                   "prediction": outputs,
                                   "answer": line['answer'],
                                   "model_id": model_name,
                                   "category": line['category'],
                                   "l2_category": line['l2_category']}) + "\n")
        ans_file.flush()
    ans_file.close()

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("--model-path", type=str, required=True, default=None)
    parser.add_argument("--num-chunks", type=int, default=1)
    parser.add_argument("--chunk-idx", type=int, default=0)
    parser.add_argument("--answers-file", type=str, default="answer.jsonl")
    parser.add_argument("--temperature", type=float, default=0.2)
    parser.add_argument("--single-pred-prompt", action="store_true")
    args = parser.parse_args()

    eval_model(args)
